package xin.marcher.module.quality.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Repository;
import xin.marcher.module.common.constants.quality.SurveyTaskConfigConstants;
import xin.marcher.module.common.core.PageResult;
import xin.marcher.module.common.enums.YesOrNoEnum;
import xin.marcher.module.common.enums.construction.ProductExceptionCode;
import xin.marcher.module.common.enums.quality.QualityAuditStatusEnum;
import xin.marcher.module.common.enums.quality.SurveyStatusEnum;
import xin.marcher.module.common.exception.BaseBizException;
import xin.marcher.module.common.exception.CommonErrorCodeEnum;
import xin.marcher.module.common.exception.ProductBizException;
import xin.marcher.module.quality.converter.SurveyTaskConverter;
import xin.marcher.module.quality.converter.SurveyTaskMaterialsRelationConverter;
import xin.marcher.module.quality.converter.SurveyTaskWhiteListConverter;
import xin.marcher.module.quality.domain.dto.ItemQualityControlSurveyTaskDTO;
import xin.marcher.module.quality.domain.dto.ItemQualityControlSurveyTaskToSellerDTO;
import xin.marcher.module.quality.domain.dto.ItemQualityControlWhiteListDTO;
import xin.marcher.module.quality.domain.entity.ItemQualityControlSurveyTaskDO;
import xin.marcher.module.quality.domain.entity.ItemQualityControlWhitelistDO;
import xin.marcher.module.quality.domain.entity.SurveyTaskMaterialsRelationDO;
import xin.marcher.module.quality.domain.request.SurveyFormRequest;
import xin.marcher.module.quality.domain.request.SurveyTaskRequest;
import xin.marcher.module.quality.domain.request.SurveyWhiteListRequest;
import xin.marcher.module.quality.mapper.ItemQualityControlSurveyTaskMapper;
import xin.marcher.module.quality.mapper.ItemQualityControlSurveyTaskMaterialsRelationMapper;
import xin.marcher.module.quality.mapper.ItemQualityControlWhitelistMapper;
import xin.marcher.module.quality.mapper.OperatorCategoryRelationMapper;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

;

/**
 *
 */
@Repository
public class SurveyRepository {
    @Resource
    private ItemQualityControlSurveyTaskMapper itemQualityControlSurveyTaskMapper;

    @Resource
    private ItemQualityControlSurveyTaskMaterialsRelationMapper itemSurveyTaskRelationMapper;

    @Resource
    private ItemQualityControlWhitelistMapper itemQualityControlWhiteListMapper;

    @Resource
    private OperatorCategoryRelationMapper operatorCategoryRelationMapper;

    @Resource
    private SurveyTaskConverter surveyTaskConverter;

    @Resource
    private SurveyTaskMaterialsRelationConverter surveyTaskMaterialsRelationConverter;

    @Resource
    private SurveyTaskWhiteListConverter whiteListConverter;


    /**
     * 根据运营人员账号分页查询调查任务列表
     *
     * @param request
     * @return
     */
    public PageResult<ItemQualityControlSurveyTaskDTO> querySurveyTaskList(SurveyTaskRequest request) {
        LambdaQueryWrapper<ItemQualityControlSurveyTaskDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(request.getUserId()), ItemQualityControlSurveyTaskDO::getUserId, request.getUserId());
        wrapper.eq(ItemQualityControlSurveyTaskDO::getDelFlag, YesOrNoEnum.YES.getCode());

        Page<ItemQualityControlSurveyTaskDO> page = new Page<>(request.getPageNo(), request.getPageSize());
        Page<ItemQualityControlSurveyTaskDO> surveyTaskDOPage = itemQualityControlSurveyTaskMapper.selectPage(page, wrapper);
        return new PageResult<>(surveyTaskConverter.converterPageResult(surveyTaskDOPage));
    }

    /**
     * 定时任务查询逾期未上传资料的任务
     *
     * @param request
     * @return
     */
    public PageResult<ItemQualityControlSurveyTaskDO> scheduleSurveyTaskList(SurveyTaskRequest request) {
        LambdaQueryWrapper<ItemQualityControlSurveyTaskDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ItemQualityControlSurveyTaskDO::getDeadlineStatus, request.getDeadlineStatus());
        wrapper.eq(ItemQualityControlSurveyTaskDO::getDelFlag, YesOrNoEnum.YES.getCode());
        wrapper.lt(ItemQualityControlSurveyTaskDO::getDeadline, request.getDeadline());

        Page<ItemQualityControlSurveyTaskDO> page = new Page<>(request.getPageNo(), request.getPageSize());
        Page<ItemQualityControlSurveyTaskDO> surveyTaskDOPage = itemQualityControlSurveyTaskMapper.selectPage(page, wrapper);
        return new PageResult<>(surveyTaskDOPage);
    }

    public void batchUnpassSurveyTaskById(List<Long> ids) {
        int count = itemQualityControlSurveyTaskMapper.batchDelSurveyTaskById(ids, QualityAuditStatusEnum.NOT_PASS.getCode());
        if (count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * 查询调查任务详情
     *
     * @param request
     * @return
     */
    public SurveyTaskMaterialsRelationDO queryMaterialsRelation(SurveyTaskRequest request) {
        LambdaQueryWrapper<SurveyTaskMaterialsRelationDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(request.getSurveyId()),
                SurveyTaskMaterialsRelationDO::getSurveyId,
                request.getSurveyId());
        wrapper.eq(SurveyTaskMaterialsRelationDO::getDelFlag, YesOrNoEnum.YES.getCode());

        SurveyTaskMaterialsRelationDO record = itemSurveyTaskRelationMapper.selectOne(wrapper);

        return record;
    }

    /**
     * 查询调查任务详情
     *
     * @param request
     * @return
     */
    public SurveyTaskMaterialsRelationDO queryMaterialsRelationBySellerId(SurveyFormRequest request) {
        LambdaQueryWrapper<SurveyTaskMaterialsRelationDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(request.getSurveyId()),
                SurveyTaskMaterialsRelationDO::getSurveyId,
                request.getSurveyId());
        wrapper.eq(SurveyTaskMaterialsRelationDO::getDelFlag, YesOrNoEnum.YES.getCode());

        SurveyTaskMaterialsRelationDO record = itemSurveyTaskRelationMapper.selectOne(wrapper);

        return record;
    }

    public ItemQualityControlSurveyTaskDO querySurveyTask(SurveyTaskRequest request) {
        // 根据userId，sellerId,调查任务id，数据生效状态，查询调查任务
        LambdaQueryWrapper<ItemQualityControlSurveyTaskDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(request.getUserId()), ItemQualityControlSurveyTaskDO::getUserId, request.getUserId());
        wrapper.eq(Objects.nonNull(request.getSurveyId()), ItemQualityControlSurveyTaskDO::getSurveyId, request.getSurveyId());
        wrapper.eq(Objects.nonNull(request.getSellerId()), ItemQualityControlSurveyTaskDO::getSellerId, request.getSellerId());

        wrapper.eq(ItemQualityControlSurveyTaskDO::getDelFlag, YesOrNoEnum.YES.getCode());
        ItemQualityControlSurveyTaskDO surveyTaskDO = itemQualityControlSurveyTaskMapper.selectOne(wrapper);

        // 如果没有查到数据，直接抛出sql异常
        if (Objects.isNull(surveyTaskDO)) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }

        return surveyTaskDO;
    }

    public ItemQualityControlSurveyTaskDO querySurveyTask(Integer surveyId) {
        // 根据userId，调查任务id，数据生效状态，查询调查任务
        LambdaQueryWrapper<ItemQualityControlSurveyTaskDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(surveyId), ItemQualityControlSurveyTaskDO::getSurveyId, surveyId);
        wrapper.eq(ItemQualityControlSurveyTaskDO::getDelFlag, YesOrNoEnum.YES.getCode());
        ItemQualityControlSurveyTaskDO surveyTaskDO = itemQualityControlSurveyTaskMapper.selectOne(wrapper);

        // 如果没有查到数据，直接抛出sql异常
        if (Objects.isNull(surveyTaskDO)) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }

        return surveyTaskDO;
    }

    /**
     * 写入调查单至调查任务中
     *
     * @param request
     * @return
     */
    public ItemQualityControlSurveyTaskDO sendSurveyForm(SurveyTaskRequest request) {
        // 根据userId，调查任务id，数据生效状态，查询调查任务
        LambdaQueryWrapper<ItemQualityControlSurveyTaskDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(request.getUserId()), ItemQualityControlSurveyTaskDO::getUserId, request.getUserId());
        wrapper.eq(Objects.nonNull(request.getSurveyId()), ItemQualityControlSurveyTaskDO::getSurveyId, request.getSurveyId());
        wrapper.eq(ItemQualityControlSurveyTaskDO::getDelFlag, YesOrNoEnum.YES.getCode());
        ItemQualityControlSurveyTaskDO surveyTaskDO = itemQualityControlSurveyTaskMapper.selectOne(wrapper);
        // 如果没有查到数据，直接抛出sql异常
        if (Objects.isNull(surveyTaskDO)) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
        // 设置调查单内容
        surveyTaskDO.setSurveyFormContent(request.getSurveyForm());
        // 设置状态为调查单已发送
        surveyTaskDO.setSurveyStatus(SurveyStatusEnum.SURVEY_FORM_SEND_STATUS.getCode());

        // 保存调查单内容到数据库
        int count = itemQualityControlSurveyTaskMapper.updateById(surveyTaskDO);
        if (count <= 0) {
            throw new ProductBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
        return surveyTaskDO;
    }

    /**
     * 审核资质证明 是否通过
     *
     * @param request
     * @return
     */
    public ItemQualityControlSurveyTaskDO auditQualityMaterials(SurveyTaskRequest request) {
        LambdaQueryWrapper<ItemQualityControlSurveyTaskDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(request.getUserId()), ItemQualityControlSurveyTaskDO::getUserId, request.getUserId());
        wrapper.eq(Objects.nonNull(request.getSurveyId()), ItemQualityControlSurveyTaskDO::getSurveyId, request.getSurveyId());
        wrapper.eq(ItemQualityControlSurveyTaskDO::getDelFlag, YesOrNoEnum.YES.getCode());

        ItemQualityControlSurveyTaskDO surveyTaskDO = itemQualityControlSurveyTaskMapper.selectOne(wrapper);
        // 如果没有查到数据，直接抛出sql异常
        if (Objects.isNull(surveyTaskDO)) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }

        // 这里的判空是为了代码能够复用，因为修改调查单状态，设置资质证明截止日期的操作是不同的逻辑
        // 但是可以共用同一个数据修改逻辑
        // 修改调查单状态
        if (Objects.nonNull(request.getAuditStatus())) {
            surveyTaskDO.setAuditStatus(request.getAuditStatus());
        }
        // 设置上传资质证明截止日期状态
        if (Objects.nonNull(request.getDeadlineStatus())) {
            surveyTaskDO.setDeadlineStatus(request.getDeadlineStatus());
        }
        // 设置上传资质证明截止日期
        if (Objects.nonNull(request.getDeadline())) {
            surveyTaskDO.setDeadline(request.getDeadline());
        }

        int count = itemQualityControlSurveyTaskMapper.updateById(surveyTaskDO);
        if (count <= 0) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_DETAIL_NULL);
        }
        return surveyTaskDO;
    }

    /**
     * 开启/关闭商家提供资质期限
     *
     * @param request
     */
    public void changeDeadlineStatus(SurveyTaskRequest request) {
        // 根据userId，调查任务id，数据生效状态，查询调查任务
        LambdaQueryWrapper<ItemQualityControlSurveyTaskDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(request.getUserId()), ItemQualityControlSurveyTaskDO::getUserId, request.getUserId());
        wrapper.eq(Objects.nonNull(request.getSurveyId()), ItemQualityControlSurveyTaskDO::getSurveyId, request.getSurveyId());
        wrapper.eq(ItemQualityControlSurveyTaskDO::getDelFlag, YesOrNoEnum.YES.getCode());
        ItemQualityControlSurveyTaskDO surveyTaskDO = itemQualityControlSurveyTaskMapper.selectOne(wrapper);
        // 如果没有查到数据，直接抛出sql异常
        if (Objects.isNull(surveyTaskDO)) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
        // 设置上传资质证明截止日期状态
        surveyTaskDO.setDeadlineStatus(request.getDeadlineStatus());
        // 设置上传资质证明截止日期
        surveyTaskDO.setDeadline(request.getDeadline());

        // 保存调查单内容到数据库
        int count = itemQualityControlSurveyTaskMapper.updateById(surveyTaskDO);
        if (count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }


    /**
     * 保存上传到OSS服务器的路径
     *
     * @param surveyTaskDO
     * @return
     */
    public void uploadQualityMaterials(ItemQualityControlSurveyTaskDO surveyTaskDO) {
        int count = itemQualityControlSurveyTaskMapper.updateById(surveyTaskDO);
        if (count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * 新增一条材料与调查任务关系
     *
     * @param relationDO
     */
    public void addQualityMaterialRelation(SurveyTaskMaterialsRelationDO relationDO) {
        int count = itemSurveyTaskRelationMapper.insert(relationDO);

        if (count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * 修改证明材料与调查任务关系
     *
     * @param relationDO
     */
    public void updateQualityMaterialRelation(SurveyTaskMaterialsRelationDO relationDO) {
        int count = itemSurveyTaskRelationMapper.updateById(relationDO);

        if (count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * 开启/关闭商家提供资质期限
     *
     * @param request
     */
    public void updateSurveyDeadline(SurveyTaskRequest request) {
        // 根据userId，调查任务id，数据生效状态，查询调查任务
        LambdaQueryWrapper<ItemQualityControlSurveyTaskDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(request.getUserId()), ItemQualityControlSurveyTaskDO::getUserId, request.getUserId());
        wrapper.eq(Objects.nonNull(request.getSurveyId()), ItemQualityControlSurveyTaskDO::getSurveyId, request.getSurveyId());
        wrapper.eq(ItemQualityControlSurveyTaskDO::getDelFlag, YesOrNoEnum.YES.getCode());
        ItemQualityControlSurveyTaskDO surveyTaskDO = itemQualityControlSurveyTaskMapper.selectOne(wrapper);
        // 如果没有查到数据，直接抛出sql异常
        if (Objects.isNull(surveyTaskDO)) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_DETAIL_NULL);
        }
        // 设置上传资质证明截止日期
        surveyTaskDO.setDeadline(request.getDeadline());

        // 保存调查单内容到数据库
        int count = itemQualityControlSurveyTaskMapper.updateById(surveyTaskDO);
        if (count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * 卖家查询调查单列表
     *
     * @param request
     * @return
     */
    public PageResult<ItemQualityControlSurveyTaskToSellerDTO> querySurveyTaskListToSeller(SurveyFormRequest request) {
        LambdaQueryWrapper<ItemQualityControlSurveyTaskDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(request.getSellerId()), ItemQualityControlSurveyTaskDO::getSellerId, request.getSellerId());
        wrapper.eq(ItemQualityControlSurveyTaskDO::getSurveyStatus, SurveyStatusEnum.SURVEY_FORM_SEND_STATUS.getCode());
        Page<ItemQualityControlSurveyTaskDO> page = new Page<>(request.getPageNo(), request.getPageSize());
        Page<ItemQualityControlSurveyTaskDO> surveyTaskDOPage = itemQualityControlSurveyTaskMapper.selectPage(page, wrapper);

        return new PageResult<>(surveyTaskConverter.converterSellerPageResult(surveyTaskDOPage));
    }

    /**
     * 查询商品白名单列表
     *
     * @param request
     * @return
     */
    public PageResult<ItemQualityControlWhiteListDTO> queryQualityWhiteList(SurveyWhiteListRequest request) {
        // 如果条件不为空，则返回的是一条
        // 如果条件为空，则返回的是所有生效的记录，按分页查询返回
        LambdaQueryWrapper<ItemQualityControlWhitelistDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(request.getSkuId()), ItemQualityControlWhitelistDO::getSkuId, request.getSkuId());
        wrapper.eq(Objects.nonNull(request.getSellerId()), ItemQualityControlWhitelistDO::getSellerId, request.getSellerId());
        wrapper.eq(Objects.nonNull(request.getActiveFlag()), ItemQualityControlWhitelistDO::getActiveFlag, request.getActiveFlag());
        // 截止生效日期大于等于请求设置的截止日期，即，到某天之后，还有多少白名单是生效的
        wrapper.ge(Objects.nonNull(request.getDeadLine()), ItemQualityControlWhitelistDO::getDeadline, request.getDeadLine());
        wrapper.eq(ItemQualityControlWhitelistDO::getDelFlag, YesOrNoEnum.YES.getCode());


        Page<ItemQualityControlWhitelistDO> page = new Page<>(request.getPageNo(), request.getPageSize());
        Page<ItemQualityControlWhitelistDO> whiteListDOPage = itemQualityControlWhiteListMapper.selectPage(page, wrapper);

        return new PageResult<>(whiteListConverter.converterPageResult(whiteListDOPage));
    }

    /**
     * 查询商品白名单列表
     *
     * @param request
     * @return
     */
    public PageResult<ItemQualityControlWhitelistDO> queryInvalidQualityWhiteList(SurveyWhiteListRequest request) {
        LambdaQueryWrapper<ItemQualityControlWhitelistDO> wrapper = Wrappers.lambdaQuery();

        wrapper.eq(ItemQualityControlWhitelistDO::getActiveFlag, YesOrNoEnum.YES.getCode());
        wrapper.lt(Objects.nonNull(request.getDeadLine()), ItemQualityControlWhitelistDO::getDeadline, request.getDeadLine());
        wrapper.eq(ItemQualityControlWhitelistDO::getDelFlag, YesOrNoEnum.YES.getCode());


        Page<ItemQualityControlWhitelistDO> page = new Page<>(request.getPageNo(), request.getPageSize());
        Page<ItemQualityControlWhitelistDO> whiteListDOPage = itemQualityControlWhiteListMapper.selectPage(page, wrapper);

        return new PageResult<>(whiteListDOPage);
    }

    /**
     * 新增一条白名单记录
     *
     * @param request
     */
    public void addIntoQualityWhiteList(SurveyWhiteListRequest request) {
        ItemQualityControlWhitelistDO whiteListDO = new ItemQualityControlWhitelistDO();
        whiteListDO.setSkuId(request.getSkuId());
        whiteListDO.setSellerId(request.getSellerId());

        if (Objects.isNull(request.getDeadLine())) {
            whiteListDO.setDeadline(DateUtils.addDays(new Date(), SurveyTaskConfigConstants.QUALITY_WHITE_LIST_DEADLINE_DAYS));
        } else {
            whiteListDO.setDeadline(request.getDeadLine());
        }
        whiteListDO.setActiveFlag(YesOrNoEnum.YES.getCode());
        whiteListDO.initCommon();

        int count = itemQualityControlWhiteListMapper.insert(whiteListDO);
        if (count <= 0) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_DETAIL_NULL);
        }
    }

    /**
     * 从品控白名单中移除
     *
     * @param request
     */
    public void removeFromQualityWhiteList(SurveyWhiteListRequest request) {
        // 如果条件不为空，则返回的是一条
        // 如果条件为空，则返回的是所有生效的记录，按分页查询返回
        LambdaQueryWrapper<ItemQualityControlWhitelistDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(request.getSkuId()), ItemQualityControlWhitelistDO::getSkuId, request.getSkuId());
        wrapper.eq(Objects.nonNull(request.getSellerId()), ItemQualityControlWhitelistDO::getSellerId, request.getSellerId());
        wrapper.eq(ItemQualityControlWhitelistDO::getDelFlag, YesOrNoEnum.YES.getCode());

        ItemQualityControlWhitelistDO whiteListDO = itemQualityControlWhiteListMapper.selectOne(wrapper);

        if (Objects.isNull(whiteListDO)) {
            throw new ProductBizException(CommonErrorCodeEnum.SQL_ERROR);
        }

        whiteListDO.setActiveFlag(YesOrNoEnum.NO.getCode());
        whiteListDO.setDelFlag(YesOrNoEnum.NO.getCode());

        int count = itemQualityControlWhiteListMapper.updateById(whiteListDO);
        if (count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    public ItemQualityControlWhitelistDO selectWhitelistDOOne(SurveyWhiteListRequest request) {
        // 如果条件不为空，则返回的是一条
        // 如果条件为空，则返回的是所有生效的记录，按分页查询返回
        LambdaQueryWrapper<ItemQualityControlWhitelistDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(request.getSkuId()), ItemQualityControlWhitelistDO::getSkuId, request.getSkuId());
        wrapper.eq(Objects.nonNull(request.getSellerId()), ItemQualityControlWhitelistDO::getSellerId, request.getSellerId());
        wrapper.eq(ItemQualityControlWhitelistDO::getDelFlag, YesOrNoEnum.YES.getCode());

        ItemQualityControlWhitelistDO whiteDO = itemQualityControlWhiteListMapper.selectOne(wrapper);

        return whiteDO;
    }


}

